#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/resource.h>

typedef struct Student{
	char* name;
	int age;
} Student;

void studentPrint(Student* student){
	printf("Student(name=%s, age=%d)\n", student->name, student->age);
}

void TestStudentPointer(int print){
	Student* student = malloc(sizeof(Student));
	student->name = "My country is China(中国大陆)";
	student->age = 26;
//	if (print % 10000000 == 0){
//		studentPrint(student);
//	}
//	free(student->name);
	free(student);
}

void showLinuxProcessUsage(){
	struct rusage usage;
	if (getrusage(RUSAGE_SELF, &usage)){
		perror("get linux process memory usage failed: ");
		exit(-1);
	}
	printf("ru_maxrss: %ld, ru_idrss: %ld, ru_isrss: %ld.\n", usage.ru_maxrss, usage.ru_idrss, usage.ru_isrss);
}

void testStringPointer(){
	showLinuxProcessUsage();
	for(int i = 0; i < 100000000; i++){
		TestStudentPointer(i);
	}
	showLinuxProcessUsage();
}

void testStructArray(){
	printf("测试StructArray");
	Student students[10];
	int length = sizeof(students)/sizeof(Student);
	printf("students's length: %d\n", length);
	for (int i = 0; i < length; i++){
		students[i].name = "should be name";
		students[i].age = i + 1;
	}

	for (int i = 0; i < length; i++){
		studentPrint(&students[i]);
	}
}

void testStructArrayPointer(){
	printf("开始测试StructArray的指针用法");
	Student array[10];
	Student * students = array;
	int length = sizeof(students)/sizeof(Student);
	printf("students's length: %d\n", length);       // length is zero
}

void testStructArrayWithMalloc(){
	printf("开始测试structArray with malloc:\n");
	int length = 10;
	Student* students = malloc(sizeof(Student) * length);
	for (int i = 0; i < length; i++){
		Student* student = students + i;
		student->name = "should be name";
		student->age = i + 1;
	}
	for(int i = 0; i < length; i++){
		studentPrint(students + i);
	}
	free(students);
}

void composeStudent(Student* student){
	student->name = "composeStudent";
}

void testStructArrayWithFunctionStr(){
	int length = 10;
	Student* students = malloc(sizeof(Student) * length);
	for (int i = 0; i < length; i++){
		composeStudent(students + i);
		(students + i)->age = i;
	}
	for (int i= 0; i < length; i++){
		studentPrint(students + i);
	}
	free(students);
}

void test_struct_pointer_array(){
	printf("start test_struct pointer array");
	Student* students[10];
	for(int i = 0; i < 10; i++){
		students[i] = malloc(sizeof(Student));
		students[i]->name = "should be name";
		students[i]->age = i;
	}

	for(int i = 0; i < 10; i++){
		studentPrint(students[i]);
		free(students[i]);
		students[i] = NULL;
	}
}

int main(int argc, char** argv){
	testStringPointer();
	testStructArray();
	testStructArrayPointer();
	testStructArrayWithMalloc();
	testStructArrayWithFunctionStr();
	test_struct_pointer_array();
	showLinuxProcessUsage();
	getchar();
}
